﻿/**
bytes = new ByteArray;
web = WebServiceControl.getInstance();
web.addArgumentWebServices(this,"gc",["uidstr","1"],URL,handler);
*/
package manager.webservice {
	import flash.events.EventDispatcher;

	/**
	 * 有关WebServices的控制接口(暂时一对一,以后更改为一对多),
	 * TODO:需要改进在同一个类下面,
	 * 如果使用多个webServices调用addArgumentWebServices
	 */
	
	public class WebServiceControl extends EventDispatcher {
		private static var _instance:WebServiceControl;
		private var webs:Vector.<FunctionData> = new Vector.<FunctionData>();

		public static function getInstance():WebServiceControl {
			if (_instance == null){
				_instance = new WebServiceControl(new SingleStance());
			}
			return _instance;
		}

		public function WebServiceControl(se:SingleStance){
			if (se == null){
				throw new Error('请使用单例');
			}
		}

		/**
		 * 进行添加webservices
		 * @param _methodName 方法名称(webserivces)
		 * @param _argu 参数(数组)
		 * @param iService 调用这个的对象
		 * @param webUrl web地址,如果为空,就调用默认的,这样就可以支持同时多个地方进行调用webservices
		 * @param callBack 回调涵数
		 */
		public function addWebService(iService:IWebServices, methodName:String, args:Vector.<Object>, 
									  webURL:String = "", callBack:Function = null):void {
			var webData:FunctionData = new FunctionData(); //Web数据处理
			webData.setData(methodName, args, iService, webURL, callBack);
			webData.addEventListener(ServicesEvent.SERVICES_FINISH_EVENT, onServiceFinish);
			webs.push(webData);
		}

		/**
		 * 添加参数的webserivces,不需要在以前进行构造,直接把参数的名称和值放到数组上,由底层来构造
		 * @param iServices  接口对象
		 * @param _methodName 方法名称(webserivces)
		 * @param _argu 参数(数组) [name,data],没有成对出现系统会报错误
		 * @param iService 调用这个的对象
		 * @param webUrl web地址,如果为空,就调用默认的,这样就可以支持同时多个地方进行调用webservices
		 * @param callBack 回调涵数
		 */
		public function addArgumentWebServices(iServices:IWebServices, methodName:String, 
											   args:Array, webURL:String = "", callBack:Function = null):void {
			if (args.length % 2 != 0){
				throw new Error('args参数不对');
			}
			//参数名，参数值
			var methodArr:Vector.<Object> = new Vector.<Object>();
			for (var i:int = 0; i < args.length; i += 2){  
				var obj:Object = new Object();
				obj.name = args[i];
				obj.data = args[i + 1];
				methodArr.push(obj);
			}
			this.addWebService(iServices, methodName, methodArr, webURL, callBack);
		}

		/**
		 * xml数据由传给回调函数 
		 * @param event
		 */		
		private function onServiceFinish(event:ServicesEvent):void {
		}

		/**
		 * 移除WebServices,遍历webs
		 * @param iServices WebServices
		 */
		public function removeWebServices(iServices:IWebServices):void {
			for (var i:int = 0; i < this.webs.length; i++){
				if (this.webs[i].iwebService == iServices){
					var web:FunctionData = this.webs.splice(i, 1)[0];
					web.dispose();
					web = null;
				}
			}
		}
	}
}

class SingleStance {
}